<template>
  <el-dialog v-if="load" :close-on-click-modal="false" title="采购接收" v-model="visible" align-center width="500px" :z-index="2000" @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top">
      <el-radio-group v-model="form.audit_result">
        <el-radio :value="1">通过</el-radio>
        <el-radio :value="2">驳回</el-radio>
      </el-radio-group><br />
      <template v-if="form.audit_result=== 1">
        <el-checkbox v-model="form.is_default" :true-value="2" :false-value="1" class="mb-2"><span class="font-bold">按照预计交期的时间默认</span></el-checkbox>
        <el-form-item v-if="form.is_default === 1" label="工厂确认出货时间" prop="pre_factory_time" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <el-date-picker v-model="form.pre_factory_time" type="date" value-format="YYYY-MM-DD" class="w-full" />
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item label="驳回原因" prop="rc_id" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.rc_id" placeholder="请选择" :options="options.rc_id" class="w-full" />
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage } from 'element-plus'
import { resMessage } from '@/utils/res'
const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const form = ref({ audit_result: 1 })
const formRef = ref()
const emit = defineEmits(['close', 'success'])

// 打开弹窗
const open = async (selection) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  const pp_ids = selection.map(d => d.pp_id)
  form.value = { audit_result: 1, pp_ids, pre_factory_time: pp_ids.length === 1 ? selection[0].pre_factory_time : '', is_default: 2 }
  loadings = reactive({})
  visible.value = true
  formRef?.value?.resetFields()
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const submit = async () => {
  if (!await formRef.value?.validate()) return
  loadings.submit = true
  api.receive(form.value).then(res => {
    resMessage({
      res,
      success: () => {
        ElMessage.success('操作成功')
        emit('success')
        close()
      }
    })
  }).finally(() => {
    loadings.submit = false
  })
}

defineExpose({ open })
</script>